<?php
declare(strict_types=1);

namespace app\common\model;

use think\Model;

class AdminToken extends Model
{
    protected $pk = 'token_id';
    
    protected $name = 'admin_token';
    
    /**
     * 保存token
     * @param int $adminId
     * @param string $token
     * @param int $expireHours token有效期(小时)
     * @return bool
     */
    public function saveToken(int $adminId, string $token, int $expireHours = 24): bool
    {
        return $this->save([
            'admin_id' => $adminId,
            'token' => $token,
            'expire_time' => date('Y-m-d H:i:s', time() + $expireHours * 3600)
        ]);
    }
    
    /**
     * 获取token信息
     * @param string $token
     * @return array|Model|null
     */
    public function getTokenInfo(string $token)
    {
        return $this->where('token', $token)
            ->where('expire_time', '>', date('Y-m-d H:i:s'))
            ->find();
    }
    
    /**
     * 清理过期的token
     * @return int
     */
    public function clearExpiredTokens(): int
    {
        return $this->where('expire_time', '<=', date('Y-m-d H:i:s'))->delete();
    }
} 